import java.util.Comparator;
import java.util.PriorityQueue;

//最小k问题 == 第k小的元素
// 思路是一样的
//https://leetcode.cn/problems/smallest-k-lcci/

class Imp implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2 - o1;
    }
}
public class LeetCodePratice {
    //时间复杂度： O(n + K*log2N)
    public static int[] smallestK(int[] array, int k) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        for(int x : array) {
            minHeap.offer(x);
        }
        int[] ret = new int[k];
        for (int i = 0; i < k; i++) {
            ret[i] = minHeap.poll();
        }
        return ret;
    }

    //此为更优
    public static int[] smallestK1(int[] array, int k) {
        //1、要找前k个元素 建立大小为k的大根堆
        //2、从第k+1个元素开始 每个元素和堆顶元素进行比较
        //   如果比堆顶元素小 则入堆
        int[] ret = new int[k];
        if (k == 0) return ret;

        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, new Imp());
        for (int i = 0; i < k; i++) {
            maxHeap.offer(array[i]);
        }
        for (int i = k; i < array.length; i++) {
            //1、获取堆顶元素的值
            int top = maxHeap.peek();
            if (top > array[i]) {
                maxHeap.poll();
                maxHeap.offer(array[i]);
            }
        }
        for (int i = 0; i < k; i++) {
            ret[i] = maxHeap.poll();
        }
        return ret;


    }


    public static void main(String[] args) {

    }
}
